package mt.controller;

import lombok.RequiredArgsConstructor;
import mt.entity.Product;
import mt.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.math.BigDecimal;
import java.util.List;

@Controller
@RequiredArgsConstructor
public class ProductController {
    private final ProductService service;

    @GetMapping("/productList")
    public String toProductList(Model model) {
        List<Product> list = service.list();
        model.addAttribute("list", list);
        return "productList";
    }

    @GetMapping("/productCreate")
    public String toUserCreate() {
        return "/productCreate";
    }

    @GetMapping("/productUpdate")
    public String toProductUpdate(Integer id, Model model) {
        Product product = service.getById(id);
        model.addAttribute("product", product);
        return "productUpdate";
    }




    @PostMapping("/productList")
    public String productList(String name, Model model) {
        List<Product> list = service.listByName(name);
        model.addAttribute("name",name);
        model.addAttribute("list", list);
        return "productList";
    }

    @PostMapping("/productCreate")
    public String productCreate(String name, BigDecimal price) {
        Product product = new Product();
        product.setName(name);
        product.setPrice(price);
        service.save(product);
        return "redirect:productList";
    }

    @PostMapping("/productUpdate")
    public String productUpdate( Product product) {
        service.updateById(product);
        return "redirect:productList";
    }

    @GetMapping("/productRemove")
    public String productRemove( Integer id) {
        service.removeById(id);
        return "redirect:productList";
    }

}
